<template>
	<form @click="upload()" enctype="multipart/form-data">
		<input
			id="update-input"
			name="file"
			type="file"
			accept=".wav"
			@change="update($event)"
			action="https://jsonplaceholder.typicode.com/posts/"
		/>
		<img :src="userUrl" alt="" />
	</form>
</template>

<script setup>
	import { computed, getCurrentInstance, reactive, ref, watch } from 'vue'
	import { ElMessage } from 'element-plus'
	import { useStore } from 'vuex'
	import { useRouter } from 'vue-router'
	import cf from '../../utils/commonFunction'

	const store = useStore()
	const { proxy } = getCurrentInstance()
	const router = useRouter()

	// props区
	const props = defineProps({
		isCircle: {
			type: Boolean,
			default: true,
		},
		borderRadius: {
			type: String,
			default: '8px',
		},
	})

	const isCircleBorder = computed(() => {
		return props.isCircle == true ? '50%' : props.borderRadius
	})

	// 显示的用户头像
	const userUrl = computed(() => {
		return (
			proxy.$storage.getItem('base64Url') ||
			store.state.userStore.blobUrl ||
			cf.getAssetsImages('default.png')
		)
	})

	const loginStatus = computed(() => {
		return proxy.$storage.getItem('loginStatus')
	})

	const blobToBase64 = (uploadFile) => {
		var reader = new FileReader()
		reader.readAsDataURL(uploadFile)
		reader.onloadend = (e) => {
			// 将base64存入vuex
			// var base64JPG = reader.result.split(';base64,')[1]
			console.log(reader.result)
			// store.state.userStore.base64Url = base64JPG
			store.state.userStore.base64Url = reader.result

			// 发送请求传输头像到后端
		}
	}
	const base64ToBlob = (base64) => {
		var arr = base64.split(',')
		var mime = arr[0].match(/:(.*?);/)[1] || 'image/png'
		// 去掉url的头，并转化为byte
		var bytes = window.atob(arr[1])
		// 处理异常,将ascii码小于0的转换为大于0
		var ab = new ArrayBuffer(bytes.length)
		// 生成视图（直接针对内存）：8位无符号整数，长度1个字节
		var ia = new Uint8Array(ab)

		for (var i = 0; i < bytes.length; i++) {
			ia[i] = bytes.charCodeAt(i)
		}

		return new Blob([ab], {
			type: mime,
		})
	}

	//获取用户信息
	const userInfo = computed(() => {
		return proxy.$storage.getItem('userInfo') || ''
	})
	const upload = () => {
		document.getElementById('update-input').click()
	}

	const update = (e) => {
		let file = e.target.files[0]
		let param = new FormData()
		param.append('File', file)

		// 判断文件类型
		console.log(param.get('File').name.replace(/.+\./, ''))
		let fileTypeList = [
			// 图片类型
			{ typeName: 'image', types: ['png', 'jpg', 'jpeg', 'bmp', 'gif'] },
			// 文本类型
			{ typeName: 'txt', types: ['txt'] },
			// excel类型
			{ typeName: 'excel', types: ['xls', 'xlsx'] },
			{ typeName: 'word', types: ['doc', 'docx'] },
			{ typeName: 'pdf', types: ['pdf'] },
			{ typeName: 'ppt', types: ['ppt'] },
			// 视频类型
			{ typeName: 'video', types: ['mp4', 'm2v', 'mkv'] },
			// 音频
			{ typeName: 'radio', types: ['mp3', 'wav', 'wmv'] },
			{ typeName: 'audio', types: ['mp3', 'wav', 'wmv'] },
		]

		if (
			fileTypeList[0].types.indexOf(
				param.get('File').name.replace(/.+\./, '')
			) > -1
		) {
			// 格式正确
			if ((param.get('File').size / 2 ** 20).toFixed(2) > 4) {
				// 做出上传限制
				ElMessage.warning('请上传小于4mb的图片')
			} else {
				// 生成blob链接
				store.state.userStore.blobUrl = URL.createObjectURL(param.get('File'))
				console.log(URL.createObjectURL(param.get('File')))
				console.log(param.get('File'))
				// 转为base64
				blobToBase64(param.get('File'))
			}
		} else {
			// 格式错误
			ElMessage.warning('请上传正确的图片格式文件！')
		}
	}

	//直接一个请求，接受到后端传过来的字节流
	// getScancode().then((res) => {
	// 	let blob = new Blob([res])
	// 	//利用这个方法生成url直接拿到标签里边用
	// 	let url = window.URL.createObjectURL(blob)
	// })

	const imageUrl = ref('')
</script>

<style scoped lang="less">
	#update-input {
		display: none;
	}
	form {
		width: 100%;
		height: 100%;
		border-radius: inherit;
		> img {
			border-radius: v-bind(isCircleBorder);
			object-fit: cover;
			width: 100%;
			height: 100%;
		}
	}
</style>
